package indi.mozping.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mongodb.BasicDBObject;
import indi.mozping.bean.QueryParamsBean;
import indi.mozping.dao.MongoDbDaoImpl;
import indi.mozping.utils.GlobalConsts;
import indi.mozping.utils.MongodbUtil;
import indi.mozping.utils.StrUtil;
import indi.mozping.utils.Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.HashMap;

/**
 * @author by mozping
 * @Classname QueryService
 * @Description TODO
 * @Date 2019/2/22 14:14
 */
@Service
public class QueryService {

    private static final Logger LOG = LoggerFactory.getLogger(QueryService.class);

    @Autowired
    MongoDbDaoImpl mongoDbDaoImpl;

    public JSONArray query(QueryParamsBean qpb) throws ParseException {

        JSONObject pageCondition = qpb.getPageParam();
        BasicDBObject whereCondition = MongodbUtil.dealWhereCondition(qpb.getWhere());
        BasicDBObject inCondition = MongodbUtil.dealInCondition(qpb.getIn());
        BasicDBObject eqCondition = MongodbUtil.dealEqCondition(qpb.getEq());
        BasicDBObject likeCondition = MongodbUtil.dealLikeCondition(qpb.getLike());
        String table = qpb.getTable();
        BasicDBObject sort = new BasicDBObject();
        boolean isApplicationSort = false;

        if (qpb.getSort() != null && !qpb.getSort().isEmpty()) {
            isApplicationSort = "application".equalsIgnoreCase(qpb.getSort().getString("mode"));
            if (!isApplicationSort) {
                sort = MongodbUtil.dealSortCondition(qpb.getSort());
            }
        }

        int skip = 0;
        int limit = 1000;

        if (pageCondition != null && !pageCondition.isEmpty()) {
            HashMap<String, Integer> pageMap = (HashMap<String, Integer>) StrUtil.getPageParams(pageCondition);
            int pageNo = pageMap.get(GlobalConsts.PAGE_NO) >= 1 ? pageMap.get(GlobalConsts.PAGE_NO) : GlobalConsts.DEFAULT_PAGE_NO;
            int pageSize = pageMap.get(GlobalConsts.PAGE_SIZE) >= 1 ? pageMap.get(GlobalConsts.PAGE_SIZE) : GlobalConsts.DEFAULT_PAGE_SIZE;
            skip = pageSize * (pageNo - 1);
            limit = pageSize;
        }

        BasicDBObject all =
                MongodbUtil.combineCondition("and", whereCondition, inCondition, eqCondition, likeCondition);

        if (isApplicationSort) {
            limit = limit * 10;
        }
        JSONArray arr = mongoDbDaoImpl.query(all, skip, limit, table, sort);

        if (isApplicationSort) {

            long begin = System.currentTimeMillis();
            arr = Util.sortDoc(arr, limit);
            System.out.println("程序排序消耗时间：" + (System.currentTimeMillis() - begin) + "ms");
        }

        return arr;
    }

}
